package chapter3.eg3;

import io.netty.util.CharsetUtil;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SocketChannel;
import java.util.concurrent.CountDownLatch;
import org.junit.Test;

public class Application {

  @Test
  public void testServer() throws IOException, InterruptedException {
    new Thread(new Reactor(8080)).start();
    CountDownLatch latch = new CountDownLatch(1);
    latch.await();
  }

  @Test
  public void testClient() throws IOException {
    SocketChannel channel = SocketChannel.open();
    channel.connect(new InetSocketAddress("127.0.0.1", 8080));
    channel.write(ByteBuffer.wrap("hello server!".getBytes()));

    ByteBuffer buffer = ByteBuffer.allocate(1024);
    channel.read(buffer);
    buffer.flip();
    byte[] bytes = new byte[buffer.remaining()];
    buffer.get(bytes);
    String message = new String(bytes, CharsetUtil.UTF_8);
    System.out.println("receive message from server: " + message);
    channel.close();
  }
}
